<?php
/**
 * Created by PhpStorm.
 * User: liuyu
 * Date: 2020/4/2
 * Time: 10:23
 */

namespace app\api\controller\v16;

use app\api\controller\v13\Auth2;
use app\common\cachemodel\Article as ArticleCacheModel;
use app\common\cachemodel\FortuneCache;
use app\common\cachemodel\GoddessBaseInfo;
use app\common\cachemodel\IndexButton;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\astrolog\Astrolog;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\AppNotice;
use app\common\model\Article;
use app\common\model\Recode as RecodeModel;
use app\common\model\Slide;
use app\everyday\controller\Index as FortuneIndex;
use Exception;
use think\Env;
use think\Log;

/**
 * @title 首页接口
 * @desc 首页获取个人太阳星座周运和上升星座周运<br/>根据版本号获取首页按钮<br/>获取星文推荐的文章十条
 * @url /api/v9/index
 * @version 2.0.0
 * Class Index
 * @package app\api\controller\v9
 */
class Index extends Auth2
{
    protected $restActionList = ['index'];

    /**
     * @title 首页接口
     * @method GET
     * @desc 无需另外传参
     * @readme /doc/api/index/index.md
     * @return array
     * @throws ApiException
     * @throws Exception
     */
    public function index()
    {
        $isYoung = $this->user ? $this->user['young_model'] : false; // 是否是青少年模式
        $time_now = time();

        if ($this->user && $this->user['rid'])
        { // 登录后
            $map = ['uid' => $this->user['id'], 'isself' => 1];
            $recode_info = (new RecodeModel())->getSelfRecode($map);

            if (empty($recode_info))
            {
                return show(config('code.denied'), '用户信息获取失败,请重新登录');
            }

            $recode_info['longitude'] = ($recode_info['long_deg'] + $recode_info['long_min'] / 60) * $recode_info['ew'];
            $recode_info['latitude'] = ($recode_info['lat_deg'] + $recode_info['lat_min'] / 60) * $recode_info['ns'];

            // 开始获取首页 日运主题 && 宜忌
            $dailyFortune = new FortuneIndex();

            //如果错误的话，也返回数据，否则首页就加载失败了
            $revive_day = ['name' => '', 'star_level' => 0, 'tips' => '', 'icon_url' => '', 'tips_url' => ''];//**之日
            $sun_in_sign = 1;//周运星座
            $tips = '';//今日天象

            //匹配返回的数据，放入缓存中
            $map = ['time' => $time_now, 'recode' => $recode_info, 'uid' => (int)$this->user['id']];
            try
            {
                $fortune_cache = (new FortuneCache())->getHomePageFortune1($map);
                //将今日运势图片替换为新图标
                $new_icon = explode('/', $fortune_cache['revive_day']['icon_url']);
                array_splice($new_icon, 5, 0, ['v2']);
                $fortune_cache['revive_day']['icon_url'] = implode('/', $new_icon);

                $sun_in_sign = (int)$fortune_cache['sun_in_sign'];
                $tips = $fortune_cache['tips'];
            }
            catch (Exception $e)
            {
                // 错误信息写入日志
                Log::write('首页获取日运缓存数据错误:' . 'uid=[' . $this->user['id'] . ']' . $e->getMessage(), 'error');
                return show(config('code.error'), '服务异常，请稍后再试~');
            }

            $todayFortune = [
//                 'pray_index' => $fortune_cache['pray_index'], // TODO 许愿临时关闭
                'pray_index' => [],
                'revive_day' => $fortune_cache['revive_day'],
                'luck_adversity' => $fortune_cache['luck_adversity'],
                'fortune_list' => $fortune_cache['fortune_list'],
            ];
            // 开启青少年模式时，禁止访问幸运星
            $luckyNeedAuth = $isYoung ? 3 : 2;
        } else
        {  // 未登录
            $sun_in_sign = $this->request->param('in_sign/d');
            if (!($sun_in_sign && in_array($sun_in_sign, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], true)))
            {
                return show(408, '请选择星座');
            }

            // 未登录，已选择星座用户，展示今日天象信息
            $tips = $this->getTips();
            $luckyNeedAuth = 2;
            $todayFortune = null;
        }

        $Article = new Article();

        $week = $Article->getFortune('week', $sun_in_sign);

        // 首页按钮
//        $btns = (new Button())->getButton(['ver' => $this->headers['version']]);
//        $btns = (new Button())->getButtons(['ver'=> $this->headers['version'],'app_type'=>$this->headers['app-type']]);
        $btns = (new IndexButton())->getIndexButton(['ver' => $this->headers['version'], 'app_type' => $this->headers['app-type']], true, $isYoung);

        if ($isYoung)
        {
            $articles = null;
            $slide = null;
        } else
        {
            // 首页轮播
            $slide = (new Slide())->getSlideVersion([]);
            foreach ($slide as $k => $datum)
            {
                $slide[$k]['image'] = $datum['image2'] ?? '';
                unset($slide[$k]['image2']);
            }
            // 获取首页文章
            $pageData = (new ArticleCacheModel())->getArticleIndexIds($this->user['id'], 2,1,20);
            $articles = $pageData['data'];
        }


        //获取公告相关信息
        $AppNotice = new AppNotice();
        $notice = $AppNotice->getNotice();
        if ($notice && (!$isYoung || ($notice['young_model'] ?? false)))
        {   // 如果为开启青少年模式 或者 青少年模式下也显示
            $notice['content'] = $notice['des'];
            //公告为jpg或gif时算出向上偏移比例【算法：（图片居中时距上的高度 - 蓝狐所给距上的高度）/ 模板或手机的高度】保留两位
            if (in_array($notice['img_type'], [2, 3]))
            {
                $notice['img_top_height'] = -0.07;//负数是向上偏移，正数是向下偏移
            }
            unset($notice['des'], $notice['young_model']);
        } else
        {
            $notice = null;
        }

        $data = [
            'in_sign' => $sun_in_sign,
            'today_astro_tips' => $tips ?? '',
            'slides' => $slide,
            'buttons' => $btns,
            'today_fortune' => $todayFortune,
            'fortune_for_week' => [
                'content' => $week['content'],
                'create_time' => date('Y-m-d', strtotime($week['publish_time'])),
                'fortune_list' => [
                    [
                        'name' => '健康',
                        'score' => (int)$week['health'],
                        'color' => '#F78BA6',
                    ],
                    [
                        'name' => '事业',
                        'score' => (int)$week['career'],
                        'color' => '#92EFF2',
                    ],
                    [
                        'name' => '爱情',
                        'score' => (int)$week['love'],
                        'color' => '#FFBD6A',
                    ],
                    [
                        'name' => '财富',
                        'score' => (int)$week['money'],
                        'color' => '#A49FF2',
                    ]
                ]
            ],
            'article' => $articles,
            'lucky_planet_switch' => true,// 幸运星功能开关
            'notice' => $notice,
            'is_young_model' => $isYoung ? 1 : 2,
            'lucky_need_auth' => $luckyNeedAuth,
            'goddess_state' => null,
            'active_switch' => [
                'is_open' => false,
                'icon' => '',
                'target' => '',
                'link' => '',
                'width' => 0,
                'height' => 0
            ]
        ];
        //青少年模式不显示女神信息
        if (!$isYoung)
        {
            //获取最新的女神动态数据
            $goddessInfo = (new GoddessBaseInfo())->getInfo();
            if ($goddessInfo)
            {
                $data['goddess_state'] = [
                    'thumb' => $goddessInfo['index_img'],
                    'title' => $goddessInfo['index_title'],
                    'des' => $goddessInfo['index_intro'],
                    'target' => $goddessInfo['index_target'],
                    'link' => htmlspecialchars_decode($goddessInfo['index_link']),
                ];
            }
        }

        $config = config('active.index_active');
        //若在活动时间内，开启
        if (active()['indexGift'] || ($time_now >= $config['start'] && $time_now <= $config['end']))
        {
            $data['active_switch'] = [
                'is_open' => false,
                'icon' => $config['icon'],
                'target' => 'link',
                'link' => Env::get('host.domain') . $config['link'],//大礼包h5
                'height' => 62
            ];
            // 仅针对V1.9.0和1.9.1开启首页幸运之城更新提示
            if (isset($this->headers['version']) && ($this->headers['version'] === '1.9.0' || $this->headers['version'] === '1.9.1'))
            {
                $data['active_switch']['is_open'] = true;
            }
        }

        // 登录后才做任务  VIP 每日任务
        if ($this->user)
        {
            (new ZlUserVip())->updateStarNum((int)$this->user['id'], 9);
        }

        return show(200, '首页加载成功', $data);
    }

    private function getTips()
    {
        //1、检测当天天象
        //2、太阳在哪个星座（输出：太阳在某某座）
        //3、水、金、火、木、土是否逆行或停滞（速度低于平均速度的1/5）（输出：某星逆行，某星停滞）
        //4、日水金火木土天海冥是否与昨天24点的星座不同（输出：某某星进入某某座）
        //5、天象是否构成大十字，大风筝，大信封，大三角，T三角（输出：大十字，大风筝，大信封等）
        $tips = '';

        $time = time();

        $timeinfo = ['year' => date('Y', $time), 'month' => date('m', $time), 'day' => date('d', $time), 'hour' => 0, 'minute' => 0,];

        $timeinfo['timezone'] = 8;

        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'], $timeinfo['minute'], 0, $timeinfo['month'], $timeinfo['day'], $timeinfo['year']) ? 1 : 0;
        // 默认北京
        $timeinfo['longitude'] = 116.443153;
        $timeinfo['latitude'] = 39.921466;

        // 获取天象盘数据
        $nowData = Astrolog::getInstance()
            ->setExecPrefix(config('astrolog.prefix'))
            ->setAdvance($timeinfo)
            ->setUserSetting(config('astroset.setting1'))
            ->setGetDatas(['now'])
            ->getAstroDatas()
            ->getDatas('now');

        $tx_planet = $nowData['planets'];// 天象行星数据

        $tx_structure = $nowData['structure'];// 天象行星结构数据


        $sun_deg = $tx_planet[0]['deg'];// 太阳的度数
        $sun_speed = $tx_planet[0]['speed'];// 太阳的度数

        $start_sign = Util::modSignId(floor($sun_deg / 30) + 1);
        $end_sign = Util::modSignId(floor(($sun_deg + $sun_speed) / 30) + 1);

        if ($start_sign == $end_sign)
        {
            $sign_name = explode('|', config('astrolog.sign_name')[$start_sign])[3];

            $tips .= '太阳运行在' . $sign_name;
        } else
        {
            $sign_name = explode('|', config('astrolog.sign_name')[$end_sign])[3];

            $tips .= '太阳进入' . $sign_name;
        }

        foreach ([2, 3, 4, 5, 6] as $i)
        {
            $speed = $tx_planet[$i]['speed'];

            $average_speed = config('astrolog.speed')[$i];

            $p_name = explode('|', config('astrolog.planets_name')[$i])[3];

            if ($speed < 0)
            {
                $tips .= '，' . $p_name . '逆行';
            }
            if ($speed <= $average_speed / 5)
            {
                $tips .= '，' . $p_name . '停滞';
            }
        }

        foreach ([2, 3, 4, 5, 6, 7, 8, 9] as $i)
        {
            $i_deg = $tx_planet[$i]['deg'];// 太阳的度数
            $i_speed = $tx_planet[$i]['speed'];// 太阳的度数

            $i_start_sign = Util::modSignId(floor($i_deg / 30) + 1);
            $i_end_sign = Util::modSignId(floor(($i_deg + $i_speed) / 30) + 1);

            if ($i_start_sign != $i_end_sign)
            {
                $i_name = explode('|', config('astrolog.planets_name')[$i])[3];

                if ($i_end_sign > 12)
                    $i_end_sign = 1;
                $i_sign_name = explode('|', config('astrolog.sign_name')[$i_end_sign])[3];

                $tips .= '，' . $i_name . '进入' . $i_sign_name;
            }
        }
        // 大十字，大风筝，大信封，大三角，T三角
        if (!empty($tx_structure['cross']))
        {
            $tips .= '，大十字';
        }
        if (!empty($tx_structure['kite']))
        {
            $tips .= '，大风筝';
        }
        if (!empty($tx_structure['envelop']))
        {
            $tips .= '，大信封';
        }
        if (!empty($tx_structure['trine']))
        {
            $tips .= '，大三角';
        }
        if (!empty($tx_structure['t_square']))
        {
            $tips .= '，T三角';
        }
        return $tips;
    }
}
